package com.ruoyi.zq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.zq.domin.ZqVolunteerTime;
import com.ruoyi.common.zq.mapper.VolunteerTimeMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.zq.service.VolunteerTimeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Objects;

/**
 *
 * @Author: LoneyFeather
 * @Date: Created in 14:12 2021/12/28
 */
@Slf4j
@Service
public class VolunteerTimeServiceImpl extends ServiceImpl<VolunteerTimeMapper, ZqVolunteerTime> implements VolunteerTimeService {

    @Autowired
    private VolunteerTimeMapper volunteerTimeMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Override
    public ZqVolunteerTime get(Long userId) {
        return getOrSave(userId);
    }

    @Override
    public int addVolunteerTime(Long userId, int time, int volunteerTime) {
        SysUser sysUser = userMapper.selectUserById(userId);
        if(ObjectUtils.isEmpty(sysUser)){
            throw new ServiceException(userId+"  用户数据不存在");
        }
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setVolunteerTime(sysUser.getVolunteerTime() - volunteerTime + time);
        return userMapper.updateUser(user);
    }

    //这是单独的表时的操作
//    @Override
//    public int addVolunteerTime(Long userId, int time) {
//        ZqVolunteerTime volunteerTime = getOrSave(userId);
//        volunteerTime.setVolunteerTime( (volunteerTime.getVolunteerTime()+time));
//        volunteerTime.setUpdateBy(SecurityUtils.getUsername());
//        volunteerTime.setUpdateTime(new Date());
//
//        return volunteerTimeMapper.updateById(volunteerTime);
//    }


    /**
     * 查询是否有这个志愿时长，没有就创建一个
     * @param userId
     * @return
     */
    public ZqVolunteerTime getOrSave(Long userId){
        ZqVolunteerTime ob = volunteerTimeMapper.selectOne(new LambdaQueryWrapper<ZqVolunteerTime>()
                .eq(ZqVolunteerTime::getUserId,userId));
        if (Objects.isNull(ob)){
            ob.setUserId(userId);
            ob.setVolunteerTime(0);
            ob.setCreateBy("auto");
            ob.setCreateTime(new Date());
            volunteerTimeMapper.insert(ob);
            log.info("添加志愿时长：{}",ob.toString());
        }
        ob =  volunteerTimeMapper.selectOne(new LambdaQueryWrapper<ZqVolunteerTime>()
                .eq(ZqVolunteerTime::getUserId,userId));
        return ob;
    }


}
